package com.delayqueue.core.permanent;

import com.delayqueue.common.task.Task;
import com.delayqueue.core.common.BeanHelper;
import com.delayqueue.core.permanent.executor.PermanentArchiveExecutor;
import com.delayqueue.core.permanent.executor.PermanentExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

@Slf4j
@Component
public class PermanentConsumer implements Runnable {

    @Autowired
    private PermanentConfig permanentConfig;

    @Autowired
    private BeanHelper beanHelper;

    private BlockingDeque<PermanentTask> queue = new LinkedBlockingDeque<>();

    protected void add(Task task, Class<? extends PermanentExecutor> classs) {
        PermanentExecutor executor = beanHelper.getBean(classs);
        if (classs == PermanentArchiveExecutor.class) {
            queue.add(new PermanentTask(task, executor));
        } else {
            if (permanentConfig.getAsync()) {
                queue.add(new PermanentTask(task, executor));
            } else {
                executor.execute(task);
            }
        }
    }

    @Override
    public void run() {
        try {
            while (true) {
                PermanentTask task = queue.take();
                task.execute();
            }
        } catch (InterruptedException e) {
            log.error("持久化任务获取失败：", e);
        }
    }
}
